# -*- coding:utf-8 -*-
import os
import random
import time

import allure
from PIL import ImageGrab
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

from PageClass.loginPageClass.loginPage import LoginPage
from PageClass.loginPageClass.publicLoginPage import PublicLoginPage

from Util import config, driverFactory, logger, ZTCCLOUDError
from Util.util import getNowTime


class LoginDepend(object):

    def __init__(self, host, user):
        self.driver = driverFactory.get_driver()
        if host in ['baseHost', 'ecsHost', 'fscHost', 'cmsHost', 'basHost', 'ledgerHost']:
            self.login = LoginPage(self.driver)
            self._login(host, user)

        elif host == 'publicHost':
            self.publicLoginPage = PublicLoginPage(self.driver)
            self._publicLogin()

    def _publicLogin(self):
        try:
            self.publicLoginPage.goto_public_login_page(config.urlDict.url.publicHost)
            self.publicLoginPage.input_account(config.urlDict.userInfo.superUser.account)
            self.publicLoginPage.input_password(config.urlDict.userInfo.superUser.password)
            self.publicLoginPage.click_login_button()
            if not self.publicLoginPage.loginSuccessOrFail():
                try:
                    WebDriverWait(self.driver, 3).until(
                        EC.visibility_of_element_located(self.publicLoginPage.intoButton))
                except Exception:
                    pass
                else:
                    self.publicLoginPage.get_into()
                    if not self.publicLoginPage.loginSuccessOrFail():
                        raise ZTCCLOUDError("公共平台登录失败")
            logger.info(f'成功登录界面：{config.urlDict.url.publicHost}')
        except Exception as e:
            img = ImageGrab.grab(all_screens=True)
            imgPath = f"{os.path.join(config.imagePath, 'wrong_picture', getNowTime().replace(':', '：'))}.png"
            img.save(imgPath)
            allure.attach.file(imgPath, '环境异常', allure.attachment_type.PNG)
            self.driver.close()
            raise AssertionError(e)

    def _login(self, host, user):
        try:
            self.login.goToLoginPage(config.urlDict.url.loginHost)
            self.login.input_account(eval(f'config.urlDict.userInfo.{user}.account'))
            self.login.input_password(eval(f'config.urlDict.userInfo.{user}.password'))
            self.login.clickLoginButton()
            if not self.login.loginSuccessOrFail():
                try:
                    WebDriverWait(self.driver, 3).until(
                        EC.visibility_of_element_located(self.login.intoButton))
                except Exception:
                    pass
                else:
                    self.login.get_into()
                    if not self.login.loginSuccessOrFail():
                        raise ZTCCLOUDError(f"登录 {eval(f'config.urlDict.url.{host}')} 失败")
            logger.info(f'成功登录界面：{host}')
            self.login.goToLoginPage(eval(f'config.urlDict.url.{host}'))
            time.sleep(random.random())
        except Exception as e:
            img = ImageGrab.grab(all_screens=True)
            imgPath = f"{os.path.join(config.imagePath, 'wrong_picture', getNowTime().replace(':', '：'))}.png"
            img.save(imgPath)
            allure.attach.file(imgPath, '环境异常', allure.attachment_type.PNG)
            self.driver.close()
            raise AssertionError(e)
